/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.quician.webapp.filters;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author quician
 */
public class SecurityFilter implements Filter{

    public static String LOGGED_USER = "LOGGED_USER";
    public static String IS_LOGGED_IN = "IS_LOGGED_IN";
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        try{
            HttpServletRequest Req = (HttpServletRequest)request;
            HttpServletResponse Resp = (HttpServletResponse) response;
            HttpSession session = Req.getSession(false);

            boolean validUser = false;
            if(session != null){
                Boolean isLoggedIn = (Boolean) session.getAttribute(IS_LOGGED_IN);

                if(Boolean.TRUE.equals(isLoggedIn)){
                    validUser = true;
                }

            }

            if(validUser){
                chain.doFilter(request, response); 
            } 
            else{
                if(session != null){
                    session.invalidate();
                }
                Resp.sendRedirect("/WebApp/login.xhtml"); 
            }
        }catch(IOException | ServletException e){
            Logger.getLogger(SecurityFilter.class.getName()).log(Level.SEVERE,"Error en el filtro de seguridad",e); 
        }
        
        
    }

    @Override
    public void destroy() {
        
    }
    
}
